<template>
  <ContentWrap>
    <template #header>
      <el-space wrap>
        <slot name="header">
          <el-button>负责人-需求-状态板</el-button>
          <el-button>负责人-需求-周板</el-button>
          <el-button>负责人-需求-月板</el-button>
          <el-button>提出人-需求-状态板</el-button>
          <el-button>提出人-需求-周板</el-button>
          <el-button>提出人-需求-月板</el-button>
        </slot> 
      </el-space>
    </template> 
    <el-table ref="table" :data="dataSet" v-adaptive="{ bottom: 50 }" style="width: 100%" border>
      <template v-for="(column, colIndex) in columnsCfg" :key="colIndex">
        <el-table-column :label="column.label + '(' + countColLabel(column, colIndex) + ')'" min-width="250">
          <template #default="scope">
            <div>
            <div v-if="colIndex < 1">
              {{ scope.row[column.property+'_name'] || scope.row[column.property+""] }}
            </div>
            <MdpDraggable v-else :itemKey="itemKey" group="group1" v-model="scope.row[column.property+'']"
              @del="(d, cb) => $emit('del', d, cb)" @edit="(d, cb) => $emit('edit', d, cb)"  @plus="(cb) => $emit('plus', cb)" :key="column.property+'_'+colIndex">
              <template #toolbar="{element,index}">
                <slot name="toolbar" :element="element" :index="index"></slot>
              </template>  
              <template #default="{ element, index }"> 
                <div  :key="colIndex + '-' + index">
                  <slot :item="element" :index="index" :colIndex="colIndex">
                    <el-row>
                      <div>{{ this.cfgCpd.x.contentFun(element, column, index, colIndex) }}</div>
                    </el-row>
                  </slot>
                </div>
              </template>
            </MdpDraggable>
          </div>
          </template>
        </el-table-column>
      </template>
    </el-table>
  </ContentWrap>
</template>

<script>
import util from '@/components/mdp-ui/js/util' //全局公共库
import MdpDraggable from '@/components/Draggable/index.vue'

export default {
  name: 'MdpKanban',
  props: {
    itemKey: {
      type: String,
      default: 'id'
    },
    cfg: {
      type: Object,
      default: () => {
        return null
      }
    },
    modelValue: {
      type: Array,
      default: ()=>{
        return []
      }
    }
  },
  data() {
    return {
      cfgInit: {
        x: {
          //第一列以外的数据列
          propertyFun: (item) => {
            //给定一个item,如何计算该字段的值
            return ''
          },
          columnsCfg: [], //如果明确知道字段列表，可以直接指定，[{property:'p1',label:'l1'},{property:'p2',label:'l2'}]
          itemCode: '', //字典编码，用于将propertyFun返回的值进行翻译成中文，并且会覆盖columnsCfg的值
          labelFun: (property, item) => {
            //如果没有字典，并且没有指定columnsCfg，则需要自定义函数进行解析名字
            return property
          },
          sort:null,
          contentFun: (item, column, rowIndex, colIndex) => {
            //默认展示的内容
            return ''
          }
        },
        y: {
          //指第一列数据

          propertyFun: (item) => {
            //给定一个item,如何计算该字段的值
            return ''
          },
          columnCfg: { property: 'colFirst', label: 'labelFirst' }, //如果明确知道字段，可以直接指定，{property:'p1',label:'l1'}
          itemCode: '', //字典编码，用于将propertyFun返回的值进行翻译成中文
          labelFun: (property, item) => {
            //如果没有字典，并且没有指定columnCfg，则需要自定义函数进行解析名字
            return property
          },
          sort: null
        }
      },
      columnsCfg: [
        /*{property:'p1',label:'l1'},{property:'p2',label:'l2'} */
      ], //表头定义
      dataSet: [
        {
          /* p1:'',p2:[],p3:[],p4:[] */
        } //每一行数据对应表头字段，每个字段下面放该字段的值，第一列必须位字符串
      ],
      dicts: {}
    }
  },
  components: { MdpDraggable },
  watch: {
    modelValue() {
      this.initData()
    },
    cfg(){
      
      this.initData()
    }
  },
  computed: { 
    cfgCpd() {
      var cfg = this.cfgInit
      if (this.cfg) {
        cfg = Object.assign(cfg, this.cfg)
      }
      return cfg
    }
  },
  methods: {
    countColLabel(column,colIndex){
      if(colIndex==0){
        return this.dataSet.length
      }
      let count=0
      this.dataSet.forEach(k=>{
        let l=k[column.property]
        if(l){
          count=count+l.length
        }
       
      })
      return count
    },
    modelValue2dataSet(modelValue) {
      let groupYMap = new Map()
      let groupYNameMap = new Map()
      let isYLabelFun = !this.cfgCpd.y.itemCode && this.cfgCpd.y.itemCode!='' && this.cfgCpd.y.labelFun
      modelValue.forEach((k) => {
        let property = this.cfgCpd.y.propertyFun(k)
        let list = groupYMap.get(property)
        if (!list) {
          list = []
        }
        list.push(k)
        groupYMap.set(property, list)
        if (isYLabelFun) {
          let label = this.cfgCpd.y.labelFun(property, k)
          groupYNameMap.set(property, label)
        }
      })
      let keysY = [...groupYMap.keys()]
      let dataSet = []
      let yProperty = this.cfgCpd.y.columnCfg.property 
      let xNameMap = new Map()
      let isXLabelFun =
        (!this.cfgCpd.x.itemCode || this.cfgCpd.x.itemCode=='') && this.cfgCpd.x.columnsCfg?.length == 0 && this.cfgCpd.x.labelFun
      keysY.forEach((k) => {
        let list = groupYMap.get(k)
        let row = {}
        row[yProperty] = k
        row[yProperty+"_name"] = groupYNameMap.get(k)
        list.forEach((item) => {
          let p = this.cfgCpd.x.propertyFun(item)
          let ls = row[p]
          if (!ls) {
            ls = []
          }
          ls.push(item)
          row[p] = ls

          if (isXLabelFun) {
            xNameMap.set(p, this.cfgCpd.x.labelFun(p, item))
          }
        })
        dataSet.push(row)
      })
      if(!this.cfgCpd.y.sort){
        dataSet.sort()
      }else{
        dataSet.sort(this.cfgCpd.y.sort)
      }


      //下面计算columnsCfg
      let columnsCfg = []
      // 1.第一列，也就是y轴的处理
      columnsCfg.push(this.cfgCpd.y.columnCfg) //y轴可以直接指定

      // 2. 第二列之后的，也就是x轴上的定义
      if (isXLabelFun) {
        let xKeys = [...xNameMap.keys()]
        if(!this.cfgCpd.x.sort){
          xKeys.sort()
        }else{
          xKeys.sort(this.cfgCpd.x.sort)
        }  
        xKeys.forEach((x) => {
          columnsCfg.push({ property: x, label: xNameMap.get(x) })
        })
      } else if (this.cfgCpd.x.itemCode?.length>0) {
        let options = this.dicts[this.cfgCpd.x.itemCode]
        if(!this.cfgCpd.x.sort){
          options.sort()
        }else{
          options.sort(this.cfgCpd.x.sort)
        } 
        options.forEach((o) => {
          columnsCfg.push({ property: o.id, label: o.name })
        })
      } else if (this.cfgCpd.x.columnsCfg) {
        columnsCfg.push(...this.cfgCpd.x.columnsCfg)
      }
      // 做一次空值赋值处理，不然拖不上去
      dataSet.forEach((k,index)=>{
        columnsCfg.forEach((c,ci)=>{
          if(ci>0){
            let l=k[c.property]
            if(!l){
              k[c.property]=[]
            }
          }
        })
      })

      return { dataSet, columnsCfg }
    },
    async initData() {
      let xItemCode = this.cfgCpd.x.itemCode
      if (xItemCode && xItemCode.length>0) {
        let xo = await this.$mdp.getDictOptions(xItemCode)
        this.dicts[xItemCode] = xo
      }
      let yItemCode = this.cfgCpd.y.itemCode
      if (yItemCode && yItemCode.length>0) {
        let yo = await this.$mdp.getDictOptions(yItemCode)
        this.dicts[yItemCode] = yo
      }
      let { dataSet, columnsCfg } = this.modelValue2dataSet(this.modelValue)
      this.dataSet = dataSet
      this.columnsCfg = columnsCfg 
        this.$refs.table?.doLayout() 
    },
  },
  mounted() {
    this.initData()
  }
}
</script>
